package net.web.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.constant.IConstant;
import net.entity.User;
import net.manager.user.UserManager;
import net.web.struts.action.form.LoginActionForm;
import net.web.util.WebUtil;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;


public class LoginAction extends DispatchAction {
	
	private static final Logger logger = Logger.getLogger(net.web.struts.action.LoginAction.class);

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginActionForm lform = (LoginActionForm) form;
		String userid = lform.getUserid();
		String password = lform.getPassword();

		User user = this.getUserManager().getUser(userid, password);
		if (user != null && user.isValid()) {
			WebUtil.setAttribute(request, IConstant.USER, user);
			return mapping.findForward("success");
		} else {
			ActionMessages messages = new ActionMessages();
			messages.add("globalmessage", new ActionMessage("invalid.user"));
			saveErrors(request, messages);
		}

		return mapping.findForward("login");
	}
	
	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		request.getSession().invalidate();
		return mapping.findForward("login");

	}
	
	private UserManager getUserManager() {
		return new UserManager();
	}
	
} //LoginAction
